<template>
  <div>
    <div class="block">
      <div class="header">
        传智教育
        <el-dropdown class="operation">
            <span class="Administrator">管理员</span>
            <span class="el-dropdown-link">
              操作<i class="el-icon-arrow-down el-icon--right"></i>
            </span>
              <el-dropdown-menu slot="dropdown">
                <el-dropdown-item>添加子部门</el-dropdown-item>
                <el-dropdown-item>编辑部门</el-dropdown-item>
                <el-dropdown-item>删除部门</el-dropdown-item>
              </el-dropdown-menu>
        </el-dropdown>
      </div>
      <el-tree
        :data="amendDepartment"
        :props="{
          label: 'name',
          children: 'children'
        }"
        node-key="id"
        default-expand-all
        :expand-on-click-node="false"
      >
        <span class="custom-tree-node" slot-scope="{ node, data }">
          <span>{{ node.label }}</span>
          <span>
            {{ data.manager }}
            <el-dropdown @command="handleCommand" class="operation">
              <span class="el-dropdown-link">
                操作<i class="el-icon-arrow-down el-icon--right"></i>
              </span>
              <el-dropdown-menu slot="dropdown">
                <el-dropdown-item
                  command="添加子部门"
                  @click.native="addSubdivision(data)"
                >
                  添加子部门
                </el-dropdown-item>
                <el-dropdown-item
                  command="编辑部门"
                  @click.native="editorialDepartment(data)"
                >
                  编辑部门
                </el-dropdown-item>
                <el-dropdown-item
                  command="删除部门"
                  @click.native="deleteDepartment(data)"
                >
                  删除部门
                </el-dropdown-item>
              </el-dropdown-menu>
          </el-dropdown>
          </span>
        </span>
      </el-tree>
      <!-- 新增部门 -->
      <el-dialog title="新增部门"
        :visible.sync="addDepartmentVisible"
        @close="ddDepartmentClose"
      >
        <el-form
          :model="department"
          :rules="rules"
          ref="department"
          label-width="100px"
          class="demo-ruleForm"
        >
          <el-form-item
            label="部门名称"
            prop="name"
          >
            <el-input
              v-model="department.name"
              placeholder="1-50个字符"
            />
          </el-form-item>
          <el-form-item
            label="部门编码"
            prop="code"
          >
            <el-input
              v-model="department.code"
              placeholder="1-50个字符"
            />
          </el-form-item>
          <el-form-item
            label="部门负责人"
            prop="manager"
          >
            <el-select
              v-model="department.manager"
              placeholder="请选择负责人"
            >
              <el-option
                v-for="item in employees"
                :key="item.id"
                :label="item.username"
                :value="item.username"
              />
            </el-select>
          </el-form-item>
          <el-form-item
            label="部门介绍"
            prop="introduce"
          >
            <el-input
              type="textarea"
              v-model="department.introduce"
              placeholder="1-300个字符"
            />
          </el-form-item>
          <el-form-item>
            <el-button @click="resetForm()">取消</el-button>
            <el-button
              @click="submitDepartment()"
              type="primary"
            >确认</el-button>
          </el-form-item>
        </el-form>
      </el-dialog>

      <!-- 编辑部门 -->
      <el-dialog title="编辑部门"
        :visible.sync="compileDepartmentVisible"
        @close="compileDepartmentClose"
      >
        <el-form
          :model="compileDepartment"
          :rules="rules" ref="department"
          label-width="100px"
          class="demo-ruleForm"
        >
          <el-form-item
            label="部门名称"
            prop="name"
          >
            <el-input
              v-model="compileDepartment.name"
              placeholder="1-50个字符"
            />
          </el-form-item>
          <el-form-item
            label="部门编码"
            prop="code"
          >
            <el-input
              v-model="compileDepartment.code"
              placeholder="1-50个字符"
            />
          </el-form-item>
          <el-form-item
            label="部门负责人"
            prop="manager"
          >
            <el-select
              v-model="compileDepartment.manager"
              placeholder="请选择选择负责人"
              @change="compileDepartmentChange(compileDepartment.manager)"
            >
              <el-option
                v-for="item in employees"
                :key="item.id"
                :label="item.username"
                :value="{
                  manager: item.username,
                  id: item.id
                }"
              >
                {{ compileDepartment.manager.manager }}
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item
            label="部门介绍"
            prop="introduce"
          >
            <el-input
              type="textarea"
              v-model="compileDepartment.introduce"
              placeholder="1-300个字符"
            />
          </el-form-item>
          <el-form-item>
            <el-button @click="amendDepartmentClose()">取消</el-button>
            <el-button
              @click="amendDepartmentOk()"
              type="primary"
            >确定</el-button>
          </el-form-item>
        </el-form>
      </el-dialog>
    </div>
  </div>
</template>

<script>
import * as departmentApi from '@/api/department'
import { mapState, mapActions, mapGetters } from 'vuex'
let num = 0
export default {
  name: 'FrameWork',
  data() {
    // 部门名称验证
    const validatePass = (rule, value, callback) => {
      if (!value.trim()) {
        callback(new Error('部门名称不能为空'));
      } else if (value.length > 50) {
        callback(new Error('部门名称为1-50个字符'));
      }
    }
    // 部门编码验证
    const validatePass1 = (rule, value, callback) => {
      if (value.trim() === '') {
        callback(new Error('部门编码不能为空'));
      } else if (value === num) {
        callback(new Error(`已经有${ num }这个编码了`));
      }
    }
    // 部门负责人验证
    const validatePass2 = (rule, value, callback) => {
      if (value.trim() === '') {
        callback(new Error('部门负责人不能为空'));
      }
    }
    // 部门介绍验证
    const validatePass3 = (rule, value, callback) => {
      if (value.trim() === '') {
        callback(new Error('部门介绍不能为空'));
      }
    }
    return {
      addDepartmentVisible: false,
      compileDepartmentVisible: false,
      department: {},
      rules: {
        name: [
          { required: true,  validator: validatePass, trigger: 'blur' }
        ],
        code: [
          { required: true,  validator: validatePass1, trigger: 'blur' }
        ],
        manager: [
          { required: true,  validator: validatePass2, trigger: 'blur' }
        ],
        introduce: [
          { required: true,  validator: validatePass3, trigger: 'blur' }
        ]
      },
      department: {
        code: '',
        introduce: '',
        manager: '',
        name: '',
        pid: '',
      },
      compileDepartment: {
        code: '',
        introduce: '',
        manager: {
          manager: '',
          id: ''
        },
        name: '',
        pid: '',
      }
    };
  },
  watch: {
    compileDepartment: {
        handler(newVal) {
            console.log(newVal);
        },
        deep: true

      },
  },
  created() {
    this.updateDepartmentList()
    this.updateGetEmployees()
  },
  computed: {
    ...mapGetters('department', [
      'amendDepartment'
    ]),
    ...mapState('department', [
      'departmentList'
    ]),
    // 获取员工简单列表
    ...mapState('employees', [
      'employees'
    ]),
  },
  methods: {
    ...mapActions('department', [
      'updateDepartmentList'
    ]),
    ...mapActions('employees', [
      'updateGetEmployees'
    ]),
    // 操作按钮
    handleCommand(data) {

    },
    // 关闭弹窗回调
    ddDepartmentClose() {
      this.department = {}
    },
    handleCommand(command) {
      console.log('xixi',command);
        this.$message('click on item ' + command);
    },
    // 添加子部门
    addSubdivision(data) {
      this.department.pid = data.id
      num = data.code
      console.log(num);
      this.addDepartmentVisible = true
    },
    xiix(id) {
      console.log('1111',id);
    },
    // 确认创建子部门
    submitDepartment() {
      this.$refs.department.validate(async (valid) => {
        if (valid) {
          await departmentApi.postDepartmentList(this.department)
            .then(msg => this.$message.success(msg))
            .catch(msg => this.$message.error(msg))

          // 请求完成后关闭窗口
          this.ddDepartmentClose()
          // 请求完成后刷新列表
          this.updateDepartmentList()
        } else {
          this.$message.error('请输入正确的表单信息');
          return false;
        }
      })
    },
    // 取消创建
    resetForm() {
      this.$refs.department.resetFields()
      this.addDepartmentVisible = false
    },
    // 编辑部门
    editorialDepartment(data) {
      this.compileDepartment.name = data.name
      this.compileDepartment.code = data.code
      this.compileDepartment.manager.manager = data.manager
      this.compileDepartment.introduce = data.introduce
      this.compileDepartmentVisible = true
    },
    // 编辑部门获取负责人id
    compileDepartmentChange(id) {
      console.log('编辑部门',id);
    },
    // 编辑部门确认修改
    amendDepartmentOk() {
      departmentApi.putDepartment({
        ...this.compileDepartment,
      })
      this.compileDepartmentClose()
    },
    // 编辑部门取消
    amendDepartmentClose() {
      this.compileDepartmentVisible = false
    },
    // 编辑部门窗口关闭
    compileDepartmentClose() {
      this.compileDepartmentVisible = false
      // 请求完成后刷新列表
      this.updateDepartmentList()
    },
    // 删除部门
    deleteDepartment(data) {
      console.log('id', data);
      this.$confirm('您是否确定要删除该部门吗?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(async () => {
          await departmentApi.deleteDepartment(data.id)
            .then(msg => {
              this.$message.success(msg)
              // 删除刷新页面
              this.updateDepartmentList()
            })
            .catch(err => this.$message.error(err))
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          });
        });
    }
  },
}
</script>

<style lang="scss" scoped>
.block {
  margin: 16px;
  padding: 30px 140px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);

  .header {
    position: relative;

    .operation {
      position: absolute;
      margin-left: 12px;
      right: 8px;

      .Administrator {
        margin-right: 12px;
      }
    }
  }

  .custom-tree-node {
    flex: 1;
    display: flex;
    align-items: center;
    justify-content: space-between;
    font-size: 14px;
    padding-right: 8px;
  }

  .operation {
    margin-left: 12px;
  }
}

</style>
